package com.guomei.controller.curse;

import com.guomei.bean.curse.ByCategoryGetAllDTO;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.CourseCategory;
import com.guomei.bean.curse.CreateOrUpdateCourseCategoryDTO;
import com.guomei.service.curse.CourseCategoryService;
import com.guomei.service.curse.CourseService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程类别表控制器
 */
@RestController
@RequestMapping("/api1/course-category")
@Slf4j
public class CourseCategoryController {
    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CourseService courseService;

    /**
     * 新增课程类别
     */
    @PostMapping("/addCourseCategory")
    public Result<?> addCourseCategory(
            @Valid @RequestBody CreateOrUpdateCourseCategoryDTO createOrUpdateCourseCategoryDTO, BindingResult result) {
        log.info("新增类别：{}", createOrUpdateCourseCategoryDTO);
        // 实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            CourseCategory courseCategory = new CourseCategory();
            courseCategory.setCategoryName(createOrUpdateCourseCategoryDTO.getCategoryName());
            courseCategory.setParentId(createOrUpdateCourseCategoryDTO.getParentId());
            courseCategory.setSortOrder(createOrUpdateCourseCategoryDTO.getSortOrder());
            courseCategory.setIcon(createOrUpdateCourseCategoryDTO.getIcon());
            courseCategory.setDescription(createOrUpdateCourseCategoryDTO.getDescription());
            courseCategory.setCreatedTime(LocalDateTime.now());
            courseCategory.setUpdatedTime(LocalDateTime.now());
            if (createOrUpdateCourseCategoryDTO.getId() != null) {
                courseCategory.setId(createOrUpdateCourseCategoryDTO.getId());
                courseCategory.setStatus(createOrUpdateCourseCategoryDTO.getStatus());
                int i = courseCategoryService.updateCourseCategory(courseCategory);
                return i > 0 ? Result.success("更新成功") : Result.fail("更新失败");
            } else {
                courseCategory.setStatus(1);
                int i = courseCategoryService.addCourseCategory(courseCategory);
                return i > 0 ? Result.success("新增成功") : Result.fail("新增失败");
            }
        } catch (Exception e) {
            log.info("新增类别失败：{}", createOrUpdateCourseCategoryDTO, e);
            return Result.fail("新增类别失败");
        }
    }

    /**
     * 根据条件查询课程类别
     * 支持的查询条件：
     * - ids: 分类ID列表（批量查询）
     * - categoryName: 分类名称（模糊查询）
     * - parentId: 父分类ID
     * - status: 状态
     * - sortOrder: 排序
     * - needCourses: 是否加载课程信息
     */
    @PostMapping("/selectByCondition")
    public Result<?> selectByCondition(@RequestBody CourseCategory courseCategory) {
        try {
            if (courseCategory == null || courseCategory.getPageNum() == null || courseCategory.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (courseCategory.getPageNum() <= 0 || courseCategory.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            Result<?> courseCategories = courseCategoryService.selectByCondition(courseCategory);
            return courseCategories;
        } catch (Exception e) {
            log.error("根据条件查询所有类别失败", e);
            return Result.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据类别id获取全部信息
     *
     */
    @PostMapping("/byCategoryGetAll")
    public Result<?> byCategoryGetAll(@RequestBody ByCategoryGetAllDTO byCategoryGetAllDTO) {
        log.info("根据类别id获取全部信息：{}", byCategoryGetAllDTO);
        try {
            Result<?> courseCategories = courseCategoryService.byCategoryGetAll(byCategoryGetAllDTO);
            return courseCategories;
        } catch (Exception e) {
            log.error("根据类别id获取全部信息", e);
            return Result.fail("根据类别id获取全部信息");
        }
    }

//    /**
//     * 测试JSON聚合查询
//     */
//    @PostMapping("/testJsonQuery")
//    public Result<?> testJsonQuery(@RequestBody Map<String, Object> request) {
//        try {
//            @SuppressWarnings("unchecked")
//            List<Long> categoryIds = (List<Long>) request.get("categoryIds");
//
//            if (categoryIds == null || categoryIds.isEmpty()) {
//                return Result.fail("categoryIds不能为空");
//            }
//
//            log.info("测试JSON聚合查询，categoryIds: {}", categoryIds);
//            List<CourseCategory> result = courseCategoryService.getCategoriesWithCoursesByIds(categoryIds);
//
//            return Result.success(result);
//        } catch (Exception e) {
//            log.error("测试JSON聚合查询失败", e);
//            return Result.fail("查询失败: " + e.getMessage());
//        }
//    }

    @PostMapping("/delete")
    public Result<?> delete(@RequestBody CourseCategory courseCategory) {
        log.info("删除类别：{}", courseCategory);
        try {
            if (courseCategory.getId() == null){
                return Result.fail("类别ID信息缺失，删除失败");
            }
            int i = courseCategoryService.deleteCourseCategoryById(courseCategory.getId());
            return i > 0 ? Result.success("删除成功") : Result.fail("删除失败");
        } catch (Exception e) {
            log.error("删除类别处理失败", e);
            return Result.fail("删除类别处理失败");
        }
    }
}
